<template>
	<view class="container">
		<view class="group-box">
			<view class="cart-list">
				<view v-if="cartList.length===0" class="nodata">
					<text class="icon iconfont icon-cart-full"></text>
					<view class="text">
						<text>购物车空空如也</text>
						<navigator url="/pages/goods/category" open-type="switchTab">点我去购物</navigator>
						
					</view>
				</view>
				<view v-for="(item, index) in cartList" :key="index" class="list-wrap">
					<view class="list-head">
						<view class="left">
							<text @click="check('group', index)" :class="{checked: item.checked}"
								class="btn-check iconfont icon-check-full"></text>
							<navigator :url="'../merchant/index?id='+item.merchantId" class="title">
								<text class="label" v-if="item.isSelf==1">自营</text>
								<text>{{item.merchantTitle}}</text>
							</navigator>
						</view>
						<view class="right">
							<text class="label" @click="openTicket(item.merchantId)">领券</text>
						</view>
					</view>
					<view v-for="(gitem, gindex) in item.goods" :key="gindex" class="list-box">
						<view class="left">
							<navigator :url="'../goods/show?id='+gitem.goodsId" class="img-box">
								<image mode="widthFix" :src="$api.loadFile(gitem.imgUrl)"></image>
							</navigator>
							<text @click="check('item',index,gindex)" :class="{checked: gitem.checked}"
								class="btn-check iconfont icon-check-full"></text>
						</view>
						<view class="right">
							<text class="title">{{gitem.title}}</text>
							<text class="attr">{{gitem.skuText}}</text>
							<view class="num-box">
								<text class="price">{{gitem.groupPrice}}</text>
								<dt-number-box class="step" :min="1" :max="gitem.stockQuantity"
									:index="{p:index,g:gindex}"
									:value="gitem.quantity>gitem.stockQuantity?gitem.stockQuantity:gitem.quantity"
									@change="numberChange"></dt-number-box>
							</view>
						</view>
						<view @click="deleteCartItem(index, gindex)" class="btn-del iconfont icon-delete"></view>
					</view>

				</view>
			</view>
		</view>
		<view v-if="cartList.length>0" class="cart-total">
			<view class="total-box">
				<view class="left">
					<view class="btn-box">
						<text :class="{active: allChecked}" @click="check('all')"
							class="btn-check iconfont icon-check-full"></text>
						<text class="btn-clear" :class="{show: allChecked}" @click="clearCart()">清空</text>
					</view>
				</view>
				<view class="center">
					<text class="price">{{totalPrice}}</text>
					<text v-if="discountPrice>0" class="tip">已优惠{{discountPrice}}元</text>
				</view>
				<view class="right">
					<text class="btn-submit" @click="confirmOrder">去结算</text>
				</view>
			</view>
		</view>
		<!--优惠券.开始-->
		<uni-popup ref="popTicket" type="bottom" @change="changeTicket">
			<view class="goods-ticket">
				<view class="head-box">
					<view class="stitle">
						<text class="title">优惠券</text>
					</view>
				</view>
				<view class="nodata" v-if="couponList.length==0">
					<text>暂无可领的优惠券..</text>
				</view>
				<scroll-view scroll-y class="list-wrap" v-else>
					<view v-for="(item,index) in couponList" :key="index" class="list-box">
						<view class="left">
							<text class="price">{{item.amount}}</text>
						</view>
						<view class="center">
							<view class="title">
								<text class="label" v-if="item.useType==1">商品券</text>
								<text class="label" v-else>店铺券</text>
								<text class="text">{{item.title}}</text>
							</view>
							<text class="time">有效期至{{item.endTime}}</text>
						</view>
						<view class="right">
							<text class="btn active" v-if="item.checked">已领取</text>
							<text class="btn" @click="addCoupon(item)" v-else>立即领取</text>
						</view>
					</view>
				</scroll-view>
				<view class="foot-box">
					<button @click="closeTicket" class="btn">确定</button>
				</view>
			</view>
		</uni-popup>
		<!--优惠券.结束-->
	</view>
</template>

<script>
	import dtNumberBox from '@/components/dt-numbox/dt-numbox.vue'
	export default {
		components: {
			dtNumberBox
		},
		data() {
			return {
				totalPrice: 0, //总金额
				discountPrice: 0, //优惠金额
				allChecked: false, //全选状态  true|false
				cartList: [], //购物车列表
				couponList: [], //优惠券列表
			}
		},
		methods: {
			//初始化数据
			async initData() {
				let _this = this;
				await _this.$api.request({
					url: `/account/shop/cart/list`,
					loading: true
				}).then(res => {
					_this.totalPrice = 0;
					_this.discountPrice = 0;
					_this.allChecked = false;
					_this.cartList = res.data;
					//console.log(res.data)
				});
			},
			//更改数量
			async numberChange(data) {
				let _this = this;
				let row = _this.cartList[data.index.p].goods[data.index.g];
				let id = row.id;
				let quantity = data.number;
				if (!quantity) {
					return false;
				}
				_this.$nextTick(async () => {
					await _this.$api.request({
						url: `/account/shop/cart/${id}?quantity=${quantity}`,
						method: "put"
					})
					row.quantity = quantity;
					_this.calcTotal();
				});
			},
			//选中状态处理
			check(type, index, gindex) {
				let _this = this;
				if (type === 'item') {
					let row = _this.cartList[index];
					let item = row.goods[gindex];
					//只有这样视图才更新
					_this.$set(item, 'checked', !item.checked);
					//检查是否全选组
					let group = row.goods.find(val => !val.checked);
					_this.$set(row, 'checked', !group);
					//检查是否全选
					let all = _this.cartList.find(val => !val.checked);
					_this.allChecked = !all;
				} else if (type === 'group') {
					//选中下面所有商品
					let row = _this.cartList[index];
					row.goods.forEach(item => {
						_this.$set(item, 'checked', !row.checked);
					});
					_this.$set(row, 'checked', !row.checked);
					//检查是否全选
					let all = _this.cartList.find(val => !val.checked);
					_this.allChecked = !all;
				} else {
					const checked = !_this.allChecked
					_this.cartList.forEach(row => {
						row.checked = checked;
						row.goods.forEach(item => {
							_this.$set(item, 'checked', checked);
						});
					})
					_this.allChecked = checked;
				}
				_this.calcTotal(type);
			},
			//删除商品
			async deleteCartItem(index, gindex) {
				let _this = this;
				let row = _this.cartList[index].goods[gindex];
				let id = row.id;
				uni.showModal({
					content: '确认要删除吗？',
					success: async (e) => {
						if (e.confirm) {
							_this.$api.request({
								url: `/account/shop/cart/${id}`,
								method: "delete"
							}).then(res => {
								//删除所选的商品
								_this.cartList[index].goods.splice(gindex, 1);
								//如果商家下面没有商品则删除商家
								if (_this.cartList[index].goods.length == 0) {
									_this.cartList.splice(index, 1);
								}
								_this.calcTotal();
								uni.showToast({
									title: '删除成功',
									icon: 'success',
									duration: 2000
								});
							});
						}
					}
				});
			},
			//清空所有商品
			async clearCart() {
				let _this = this;
				uni.showModal({
					content: '确认要删除所有商品吗？',
					success: async (e) => {
						if (e.confirm) {
							// 遍历每个商家
							for (let i = 0; i < _this.cartList.length; i++) {
								// 遍历每个商家下的所有商品
								for (let j = 0; j < _this.cartList[i].goods.length; j++) {
									let id = _this.cartList[i].goods[j].id;
									// 发送删除请求
									await _this.$api.request({
										url: `/account/shop/cart/${id}`,
										method: "delete"
									});
								}
							}
							// 清空购物车列表
							_this.cartList = [];
							// 重新计算总价
							_this.calcTotal();
							// 显示成功提示
							uni.showToast({
								title: '所有商品删除成功',
								icon: 'success',
								duration: 2000
							});
						}
					}
				});
			},



			//计算总价
			calcTotal() {
				let list = this.cartList;
				if (list.length === 0) {
					this.totalPrice = 0;
					this.discountPrice = 0;
					return;
				}
				let total = 0;
				let original = 0;
				list.forEach(row => {
					row.goods.forEach(item => {
						if (item.checked) {
							original += item.sellPrice * item.quantity;
							total += item.groupPrice * item.quantity;
						}
					});
				});
				this.totalPrice = Number(total.toFixed(2));
				this.discountPrice = Number((original - total).toFixed(2));
			},
			//打开弹窗
			openTicket(id) {
				let _this = this;
				//加载优惠券列表
				_this.$api.request({
					url: `/client/shop/coupon/view/10?merchantId=${id}`,
					loading: true
				}).then(res => {
					_this.couponList = res.data;
					_this.$refs.popTicket.open();
				});
			},
			//关闭弹窗
			closeTicket() {
				this.couponList = [];
				this.$refs.popTicket.close();
			},
			//弹窗回调
			changeTicket(e) {
				if (e.show) {
					uni.hideTabBar();
				} else {
					uni.showTabBar();
				}
			},
			//领取优惠券
			addCoupon(val) {
				let _this = this;
				_this.$api.request({
					url: `/account/shop/coupon/add`,
					method: "post",
					data: {
						couponId: val.id
					}
				}).then(res => {
					uni.showToast({
						title: '领取成功',
						icon: 'success',
						duration: 2000
					});
				});
				_this.$set(val, 'checked', true);
			},
			//创建订单
			confirmOrder() {
				let goodsData = [];
				this.cartList.forEach(item => {
					item.goods.forEach(gitem => {
						if (gitem.checked) {
							goodsData.push({
								productId: gitem.productId,
								quantity: gitem.quantity
							})
						}
					})
				});
				if (goodsData.length === 0) {
					uni.showToast({
						title: '请选择购物车商品',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				uni.navigateTo({
					url: `/pages/order/confirm?type=0&data=${JSON.stringify(goodsData)}`
				})
			},
		},
		//页面初始化
		onShow(options) {
			this.initData();
		}
	}
</script>

<style lang="scss">
	.cart-total {
		height: 51px;

		.total-box {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 50px;
			/* #ifdef MP */
			bottom: 0;
			/* #endif */
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 24rpx;
			height: 100rpx;
			background: #fff;
			border-top: 2rpx solid rgba($color: #000, $alpha: 0.05);
			border-bottom: 2rpx solid rgba($color: #000, $alpha: 0.05);
			-webkit-overflow-scrolling: touch;

			.left {
				.btn-box {
					position: relative;

					.btn-check {
						position: absolute;
						top: 50%;
						left: 0;
						margin-top: -26rpx;
						width: 52rpx;
						height: 52rpx;
						color: #C0C4CC;
						font-size: 52rpx;
						line-height: 1;
						background: #fff;
						border-radius: 52rpx;
						z-index: 1;

						&.active {
							color: #fa436a;
						}
					}

					.btn-clear {
						display: block;
						margin-left: 24rpx;
						color: #fff;
						font-size: 28rpx;
						line-height: 52rpx;
						width: 0;
						height: 52rpx;
						overflow: hidden;
						background: #C0C4CC;
						border-radius: 0 52rpx 52rpx 0;
						opacity: 0;
						transition: .2s;

						&.show {
							opacity: 1;
							padding: 0 26rpx 0 38rpx;
							width: auto;
						}
					}
				}
			}

			.center {
				flex-grow: 1;
				padding: 0 24rpx;
				text-align: right;

				.price {
					display: block;
					color: #ff5000;
					font-size: 32rpx;
					font-weight: bold;
					line-height: 40rpx;

					&::before {
						content: "￥";
						font-size: 24rpx;
						font-weight: 500;
					}
				}

				.tip {
					display: block;
					color: #999;
					font-size: 20rpx;
					line-height: 28rpx;
				}
			}

			.right {
				.btn-submit {
					display: block;
					padding: 0 48rpx;
					color: #fff;
					font-size: 30rpx;
					line-height: 76rpx;
					height: 76rpx;
					background: #ff722c;
					border-radius: 76rpx;
				}
			}
		}
	}
</style>